'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';

interface SaveDestinationButtonProps {
  destinationId: string;
  initialSaved: boolean;
}

export function SaveDestinationButton({ destinationId, initialSaved }: SaveDestinationButtonProps) {
  const [isSaved, setIsSaved] = useState(initialSaved);
  const [isLoading, setIsLoading] = useState(false);
  const router = useRouter();

  useEffect(() => {
    setIsSaved(initialSaved);
  }, [initialSaved]);

  const handleSave = async () => {
    try {
      setIsLoading(true);
      const response = await fetch(`/api/destinations/${destinationId}/save`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
      });

      if (!response.ok) {
        throw new Error('保存失败');
      }

      const data = await response.json();
      setIsSaved(data.saved);
      
      // 强制刷新所有相关页面
      router.refresh();
    } catch (error) {
      console.error('保存失败:', error);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <button
      onClick={handleSave}
      disabled={isLoading}
      className={`inline-flex items-center px-4 py-2 rounded-md text-sm font-medium transition-colors duration-200 ${
        isSaved
          ? 'bg-red-100 text-red-700 hover:bg-red-200'
          : 'bg-blue-100 text-blue-700 hover:bg-blue-200'
      } disabled:opacity-50`}
    >
      <svg
        className={`-ml-1 mr-2 h-5 w-5 transition-colors duration-200 ${
          isSaved ? 'text-red-500' : 'text-blue-500'
        }`}
        xmlns="http://www.w3.org/2000/svg"
        fill={isSaved ? 'currentColor' : 'none'}
        viewBox="0 0 24 24"
        stroke="currentColor"
      >
        <path
          strokeLinecap="round"
          strokeLinejoin="round"
          strokeWidth={2}
          d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"
        />
      </svg>
      {isLoading ? '处理中...' : (isSaved ? '已收藏' : '收藏')}
    </button>
  );
} 